package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import ModelLayer.Discount;

public class DBDiscount implements IFDBDiscount {
	private Connection con;

	public DBDiscount() {
		con = DBConnection.getInstance().getDBcon();
	}

	@Override
	public Discount getDiscount(int discountId) {
		String wClause = "  discountId = '" + discountId + "'";
		return singleWhere(wClause);
	}

	@Override
	public void insertDiscount(Discount discount) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public ArrayList<Discount> getAllDiscount() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Discount updateDiscount(int discountId) {
		// TODO Auto-generated method stub
		return null;
	}

	private Discount singleWhere(String wClause) {
		ResultSet results;

		Discount discount = new Discount();
		String query = buildQuery(wClause);
		System.out.println(query);
		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);
			if (results.next()) {
				discount = buildDiscount(results);
				stmt.close();

			}
		} catch (Exception e) {
			// TODO need to throw exception class
			System.out.println("Query exception: " + e);
		}
		return discount;
	}

	private ArrayList<Discount> miscWhere(String wClause) {
		ResultSet results;
		ArrayList<Discount> list = new ArrayList<Discount>();
		String query = buildQuery(wClause);
		try {
			Statement stmt = con.createStatement();
			stmt.setQueryTimeout(5);
			results = stmt.executeQuery(query);

			while (results.next()) {
				Discount discount = new Discount();
				discount = buildDiscount(results);
				list.add(discount);
			}
			stmt.close();

		} catch (Exception e) {
			System.out.println("Query exception - select: " + e);
			e.printStackTrace();
		}
		return list;
	}

	private Discount buildDiscount(ResultSet results) {
		Discount discount = new Discount();
		try {
			discount.setDiscountId(results.getInt("discountId"));
			discount.setDiscountPercentage(results.getDouble("discountPercent"));
			discount.setMinPriceRequired(results.getInt("minRequirePrice"));

		} catch (Exception e) {
			// TODO need to throw exception class
			System.out.println("error in building the customer object");
		}
		return discount;
	}

	private String buildQuery(String wClause) {
		String query = "SELECT discountId, discountPercent, minRequirePrice FROM discount";
		if (wClause.length() > 0) {
			query = query + " WHERE" + wClause;
		}
		return query;
	}

}
